package com.yf.provider;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyProvider extends ContentProvider {

	private MyOpenHelper openHelper;
	private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	private static final int QUERY_MATCHED = 0;
	private static final int INSERT_MATCHED = 1;
	private static final int UPDATE_MATCHED = 2;
	private static final int DELETE_MATCHED = 3;
	
	static {
		//给当前的URI匹配器添加一个匹配规则
		sURIMatcher.addURI("com.yf.provider", "query", QUERY_MATCHED);
		sURIMatcher.addURI("com.yf.provider", "insert", INSERT_MATCHED);
		sURIMatcher.addURI("com.yf.provider", "update", UPDATE_MATCHED);
		sURIMatcher.addURI("com.yf.provider", "delete", DELETE_MATCHED);
	}

	@Override
	public boolean onCreate() {
		openHelper = new MyOpenHelper(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		int r = sURIMatcher.match(uri);
		if (r == QUERY_MATCHED) {
			SQLiteDatabase db = openHelper.getReadableDatabase();
			return db.query("user", projection, selection, selectionArgs, null, null, sortOrder);
		}
		
		return null;
	}

	@Override
	public String getType(Uri uri) {
		
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int r = sURIMatcher.match(uri);
		if (r != INSERT_MATCHED) {
			return null;
		}
		SQLiteDatabase db = openHelper.getReadableDatabase();
		long rowId = db.insert("user", null, values);
		
		ContentResolver resolver = getContext().getContentResolver();
		// 通过内容解析者发出一个数据变化的通知
		// 参数一：只有能匹配uri的内容观察者会收到通知
		// 参数二：内容观察者对象，null表示这个uri的所有观察者都可以收到通知
		resolver.notifyChange(uri, null);
		return Uri.parse(String.valueOf(rowId));
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int r = sURIMatcher.match(uri);
		if (r != DELETE_MATCHED) {
			return 0;
		}
		
		SQLiteDatabase db = openHelper.getReadableDatabase();
		return db.delete("user", selection, selectionArgs);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		int r = sURIMatcher.match(uri);
		if (r != UPDATE_MATCHED) {
			return 0;
		}
		
		SQLiteDatabase db = openHelper.getReadableDatabase();
		return db.update("user", values, selection, selectionArgs);
	}

}
